﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Utils.ContentManagement;
using Microsoft.Xna.Framework;
using Utils.Drawing;

namespace Utils.Debugging
{
    public class DebugHud
    {
        int frameRate;
        int frameCount;
        int lowMem;
        int lastMem;
        float timeAcc;
        SpriteFont font;
        TextField txtFrames;
        TextField txtMemory;
        TextField txtVersion;

        public void Init(ContentLoader loader, Vector2 pos, string appVersion)
        {
            font = loader.Load<SpriteFont>("Fonts/Debugging");

            txtFrames = new TextField(font, 50);
            txtFrames.Origin = TextField.ORIGIN_TOP_LEFT;
            txtFrames.Pos = pos;

            txtMemory = new TextField(font, 50);
            txtMemory.Origin = TextField.ORIGIN_TOP_LEFT;
            txtMemory.Pos = pos + Vector2.UnitY * 15;

            txtVersion = new TextField(font, 16);
            txtVersion.Origin = TextField.ORIGIN_TOP_LEFT;
            txtVersion.Pos = pos + Vector2.UnitY * 30;
            txtVersion.Text.Set("Ver ").Append(appVersion);
        }

        public void Draw(float dTime)
        {
            timeAcc += dTime;
            frameCount++;
            if (timeAcc > 1)
            {
                if (timeAcc > 1.5f)
                {
                    timeAcc = 0;
                }
                else
                {
                    timeAcc -= 1;
                }
                frameRate = frameCount;
                frameCount = 0;
            }

            SpriteRenderer renderer = SpriteRenderer.DEFAULT;

            int mem = (int)GC.GetTotalMemory(false) / 1024;
            if (mem < lastMem)
            {
                lowMem = mem;
            }

            renderer.Begin(SpriteSortMode.Immediate);
            {
                txtFrames.Text.Set("Frames: ").Append(frameRate);
                txtFrames.Draw(renderer);

                txtMemory.Text.Set("Mem: ").Append(mem).Append(" (").Append(lowMem).Append(") KB");
                txtMemory.Draw(renderer);

                txtVersion.Draw(renderer);
            }
            renderer.End();

            lastMem = mem;
        }
    }
}
